/**
 * Copyright (C) 2010 altuure <altuure [AT] gmail [DOT] com> http://www.altuure.com/projects/yagdao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.altuure.yagdao.blog.service.impl;

import com.altuure.yagdao.blog.dao.RoleDAO;
import com.altuure.yagdao.blog.dao.UserDAO;
import com.altuure.yagdao.blog.model.Role;
import com.altuure.yagdao.blog.model.User;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;

@Transactional
public class UserServiceImpl implements UserDetailsService{
    private UserDAO userDAO;
    private RoleDAO roleDAO;
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        User user=userDAO.findByUsername(username);
        if(user==null)return null;
        final List<Role> roleList = roleDAO.getRoles(username);
        final HashSet<GrantedAuthority> auths = new HashSet<GrantedAuthority>();
        for (Role role : roleList) {
            auths.add(new GrantedAuthorityImpl(role.getName()));
        }
        
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),true,true,true,true, auths);
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

}
